/***************************************************
> Copyright (C) 2025 ==LENA== All rights reserved.
> File Name: client.c
> Author: lena
> Mail:lena_li@126.com 
> Created Time: 2025年01月03日 星期五 16时32分43秒
***************************************************/
//发送客户端
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "cJSON.h"
struct sockaddr_in* seraddr;

int sock_create(const char* server_addr,int port);
void add_data();
void cutStringByFour(const char *input);
void send_all_data();

//创建sock;
int sock_create(const char* server_addr,int port)
{
	//printf("111111\n");
	int sock = socket(AF_INET,SOCK_STREAM,0);
	//printf("111111\n");
	int ret = 0;
	if(sock == -1)
	{
		perror("socket");
		exit(-1);
	}
	//定义地址
	struct sockaddr_in *seraddr = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in));
	if (seraddr == NULL) 
	{
        perror("malloc");
        close(sock);
        return -1;
    }
	memset(seraddr,0,sizeof(struct sockaddr_in));

	seraddr->sin_family = AF_INET;
	//printf("111111\n");
	seraddr->sin_addr.s_addr = inet_addr(server_addr);
	//printf("111111\n");
	//htons：转化为可以java理解的
	seraddr->sin_port = htons(port);
	return sock;
}

//申请发送广播
void add_data()
{
	int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) 
	{
        perror("socket");
        exit(-1);
    }

    // 连接服务器
    if (connect(sock, (struct sockaddr *)seraddr, sizeof(struct sockaddr_in)) == -1) 
	{
        perror("connect");
        exit(-1);
    }

    cJSON *json = NULL;
    char type[20] = "send_data_signal";
    json = cJSON_CreateObject();
    cJSON_AddItemToObject(json, "type", cJSON_CreateString(type));   
    char *dest = NULL;
    dest = cJSON_Print(json);
    char buf[100] = {0};
    memcpy(buf, dest, strlen(dest));
    // 使用send函数发送数据，因为是TCP协议
    int ret = send(sock, buf, strlen(buf), 0);
    if (ret == -1) 
	{
        printf("send add_data_signal\n");
        exit(-1);
    }

    // 接收结果
    char result[100] = {0};
    memset(&result, 0, sizeof(result));
    // 使用recv函数接收数据，因为是TCP协议
    ret = recv(sock, result, sizeof(result), 0);
    if (ret == -1) 
	{
        printf("recv add_data_signal");
        exit(-1);
    }
	//读取服务器端传来的客户端ID
    cJSON *node = NULL;
    json = cJSON_Parse(result);
    node = cJSON_GetObjectItem(json, "can_send_ID");
    if (node == NULL) 
	{
        printf("can't find ID\n");
		cJSON_Delete(json); 
        close(sock);        
    }
    else if (node->type == cJSON_String) 
	{
     char can_send_ID[100] = {0};   
        strcpy(can_send_ID, node->valuestring);
		//将收到的字符串切割开用于阅读
		cutStringByFour(can_send_ID);
		cJSON_Delete(json); 
        close(sock);
    }
	cJSON_Delete(json);
    close(sock);   
}

//将收到的字符串(以4为单位)切割开
void cutStringByFour(const char *input) 
{
    int len = strlen(input);
	printf("可发送的客户端ID有：\n");
    for (int i = 0; i < len; i += 4) 
	{
        char part[5];  // 用于存储切割出来的每一部分，长度为4 + 1（预留'\0'结尾）
        int copyLen = (i + 4 < len)? 4 : len - i;  // 判断剩余长度，避免越界
        strncpy(part, input + i, copyLen);
        part[copyLen] = '\0';  // 确保字符串结尾有'\0'
        printf("%s\n", part);		
    }
}

//发送最后的文件
void send_all_data()
{
	int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) 
	{
        perror("socket");
        exit(-1);
    }

    // 连接服务器
    if (connect(sock, (struct sockaddr *)seraddr, sizeof(struct sockaddr_in)) == -1) 
	{
        perror("connect");
        exit(-1);
    }

    cJSON *json = NULL;
    char type[20] = "all_data";
    json = cJSON_CreateObject();
    cJSON_AddItemToObject(json, "type", cJSON_CreateString(type));
	char send_ID[100] = {0};
	printf("请输入你想要接收广播的ID\n");
	scanf("%s",send_ID);
	cJSON_AddItemToObject(json, "send_ID", cJSON_CreateString(send_ID));
	char send_data[100] = {0};
	printf("请输入广播的内容\n");
	scanf("%s",send_data);
	cJSON_AddItemToObject(json, "send_data", cJSON_CreateString(send_data));
    char *dest = NULL;
    dest = cJSON_Print(json);
    char buf[1024] = {0};
    memcpy(buf, dest, strlen(dest));
    // 使用send函数发送数据，因为是TCP协议
    int ret = send(sock, buf, strlen(buf), 0);
    if (ret == -1) 
	{
        printf("send all_data\n");
        exit(-1);
    }
	printf("发送成功\n");    
	cJSON_Delete(json);
    close(sock);
   
}
 

int main(int argc, const char* argv[]) {
    // 调用sock_create函数创建套接字
    int sock = sock_create("127.0.0.1", 6868);
    if (sock == -1) 
	{
        printf("Failed to create sock.\n");
        return -1;
    }
    // 注册
    printf("欢迎来到广播分发系统！\n");
	printf("是否添加广播？\n");
	printf("1---添加\n");
    printf("2---退出\n");
	int val = 0;
	scanf("%d",&val);
	switch(val)
	{
		case 1:
		//接收客户端ID
		add_data();
		//发送目标客户端和广播内容
		send_all_data();		
		break;
		case 2:
		printf("退出成功\n");
		break;
		default:
		printf("输入错误，自动退出\n");
		break;
	}
}